package com.tsx.leetcode.hot100.medium;

import com.tsx.leetcode.hot100.common.ListNode;

public class Q2AddTwoNumbers {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(3);
        ListNode l4 = new ListNode(8);
        ListNode l5 = new ListNode(8);
        ListNode l6 = new ListNode(9);
        l1.next = l2;
        l2.next = l3;
        l4.next = l5;
        l5.next = l6;
        Q2AddTwoNumbers q2AddTwoNumbers = new Q2AddTwoNumbers();
        ListNode head = q2AddTwoNumbers.addTwoNumbers(l1, l4);
        ListNode.printLinkedList(head);
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0); // 虚拟头节点
        ListNode curr = dummy;
        int carry = 0;

        while (l1 != null || l2 != null) {
            int x = l1 == null ? 0 : l1.val; // 处理边界情况
            int y = l2 == null ? 0 : l2.val; // 若位数不对齐的话就是0
            int sum = x + y + carry; // 相加要算上之前的进位值
            carry = sum / 10; // 进位值每次都会更新
            curr.next = new ListNode(sum % 10); // 处理新的节点的值
            curr = curr.next; // 新的节点也要往前移
            if (l1 != null) { // 不为空的时候再往前移
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (carry != 0) {
            curr.next = new ListNode(carry);
        }
        return dummy.next;
    }

}
